-- | Hexena.Codec.Parser.ParseRawSections
-- 
-- <This file is a part of Hexena - Haskell Executable Analyser>
-- 
-- See Hexena.hs for License Information.
-- 
-- This will just parse the raw sections from disk and it can be specifically parsed
-- as a Data Directory Downstream.
module Hexena.Codec.Parser.ParseRawSections (parseRawSections) where

import qualified Data.ByteString.Lazy as L

import Data.Binary.Get
import Data.Word
import Data.Int (Int64)
import Control.Monad (mapM)

import Hexena.Data.SectionHeader

parseRawSections :: [Section] -> Get RawSections
parseRawSections sectionLs = do
    -- First lets slurp up the null bytes to the first actual real section.
    --
    -- To accomplish this some assumptions are made, which should be revisited later
    -- to make failsafes.  But we are assuming that all of the sections are in order and
    -- our current position is just after the section table and before the sections.
    currPos <- bytesRead
    nulpad <- getLazyByteString (fstPtr - currPos)

    -- getLazyByteString accepts Int64
    gobbledSections <- mapM getLazyByteString ptrToSz

    return $ RawSections nulpad gobbledSections
  where
    ptrToRaw = filter (/= (0 :: Word32)) $ fmap (get ptrToRawData) sectionLs
    ptrToSz  = map fromIntegral (filter (/= (0 :: Word32)) $ fmap (get sizeOfRawData) sectionLs) :: [Int64]
    fstPtr = fromIntegral $ ptrToRaw !! 0 :: Int64
-- need to have a tuple for null padding, then list of tuples for sections
